package com.lanou.myim.tools;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactManager;
import com.easemob.exceptions.EaseMobException;
import com.lanou.myim.application.BaseApplication;
import com.lanou.myim.entity.CommentEty;
import com.lanou.myim.entity.EventBusConstant;
import com.parse.DeleteCallback;
import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.GetDataCallback;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.SaveCallback;

import java.io.ByteArrayOutputStream;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import de.greenrobot.event.EventBus;


/**
 * Created by dllo on 16/3/9.
 */
public class ParseSingleton {
    static ParseObject parseObject;
    private static List<String> friendList;


    public static void setBitmap(final String userName, final ImageView imageView) {
        ParseQuery<ParseObject> query = ParseQuery.getQuery("accountPicture");
        query.whereEqualTo("userName", userName);
        query.getFirstInBackground(new GetCallback<ParseObject>() {
            @Override
            public void done(ParseObject object, ParseException e) {
                if (object != null) {
                    ParseFile file = object.getParseFile("picture");
                    if (file!=null){
                    file.getDataInBackground(new GetDataCallback() {
                        @Override
                        public void done(byte[] data, com.parse.ParseException e) {
                            if (data != null) {
                                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                                imageView.setImageBitmap(bitmap);
                            }
                        }
                    });}

                }
            }
        });
    }




    public static void setDescr(final String userName, final TextView textView) {

        ParseQuery<ParseObject> query = ParseQuery.getQuery("accountPicture");
        query.whereEqualTo("userName", userName);
        query.getFirstInBackground(new GetCallback<ParseObject>() {
            @Override
            public void done(ParseObject object, ParseException e) {
                if (object != null && object.getString("descr") != null) {
                    String str = object.getString("descr");
                    textView.setText(str);
                }
            }
        });

    }

    public static void insertOrModifyDescr(final String userName, final String descr) {
        ParseQuery<ParseObject> query = ParseQuery.getQuery("accountPicture");
        final ParseObject accountInformation = new ParseObject("accountPicture");
        query.whereEqualTo("userName", userName);
        query.getFirstInBackground(new GetCallback<ParseObject>() {
            @Override
            public void done(ParseObject object, ParseException e) {
                if (object == null) {
                    accountInformation.put("userName", userName);
                    accountInformation.put("descr", descr);
                    accountInformation.saveInBackground(new SaveCallback() {
                        @Override
                        public void done(ParseException e) {
                            Toast.makeText(BaseApplication.applicationContext, "备注已存储", Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    object.put("descr", descr);
                    object.saveInBackground(new SaveCallback() {
                        @Override
                        public void done(ParseException e) {
                            Toast.makeText(BaseApplication.applicationContext, "备注已更改", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });


    }


    public static void insertOrModifyPicture(final String userName, final Bitmap bitmap) {
        final ParseObject accountInformation = new ParseObject("accountPicture");

        ParseQuery<ParseObject> query = ParseQuery.getQuery("accountPicture");
        query.whereEqualTo("userName", userName);
        query.getFirstInBackground(new GetCallback<ParseObject>() {
            @Override
            public void done(ParseObject object, ParseException e) {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                byte[] datas = outputStream.toByteArray();
                ParseFile pf = new ParseFile("icon.png", datas);
                pf.saveInBackground();
                if (object == null) {
                    accountInformation.put("userName", userName);
                    accountInformation.put("picture", pf);
                    accountInformation.saveInBackground(new SaveCallback() {
                        @Override
                        public void done(ParseException e) {
                            Toast.makeText(BaseApplication.applicationContext, "头像已保存", Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    object.put("picture", pf);
                    object.saveInBackground(new SaveCallback() {
                        @Override
                        public void done(ParseException e) {
                            Toast.makeText(BaseApplication.applicationContext, "头像已更新", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }});
    }


    public static void insertOrModifyPersonPicture(final String userName, final Bitmap bitmap) {
        final ParseObject accountInformation = new ParseObject("accountPicture");

        ParseQuery<ParseObject> query = ParseQuery.getQuery("accountPicture");
        query.whereEqualTo("userName", userName);
        query.getFirstInBackground(new GetCallback<ParseObject>() {
            @Override
            public void done(ParseObject object, ParseException e) {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                byte[] datas = outputStream.toByteArray();
                ParseFile pf = new ParseFile("icon.png", datas);
                pf.saveInBackground();
                if (object == null) {
                    accountInformation.put("userName", userName);
                    accountInformation.put("picture", pf);
                    accountInformation.saveInBackground(new SaveCallback() {
                        @Override
                        public void done(ParseException e) {
                            Toast.makeText(BaseApplication.applicationContext, "头像已保存", Toast.LENGTH_SHORT).show();
                            EventBus.getDefault().post(EventBusConstant.REFRESH_CIRCLE_OF_FRIENDS);
                        }
                    });
                } else {
                    object.put("picture", pf);
                    object.saveInBackground(new SaveCallback() {
                        @Override
                        public void done(ParseException e) {
                            Toast.makeText(BaseApplication.applicationContext, "头像已更新", Toast.LENGTH_SHORT).show();
                            EventBus.getDefault().post(EventBusConstant.REFRESH_CIRCLE_OF_FRIENDS);
                        }
                    });
                }
            }});
    }






    public static void deleteParseObject(String userName) {
        ParseQuery query = ParseQuery.getQuery("accountPicture");
        query.whereEqualTo("userName", userName);
        query.getFirstInBackground(new GetCallback() {
            @Override
            public void done(ParseObject object, ParseException e) {
                if (object != null) {
                    object.deleteInBackground(new DeleteCallback() {
                        @Override
                        public void done(ParseException e) {
                            Toast.makeText(BaseApplication.applicationContext, "已删除", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

            @Override
            public void done(Object o, Throwable throwable) {

            }
        });
    }

    public static void publishIdea(final String userName, final String ideaBody) {
        ParseObject publishInformation = new ParseObject("personalIdea");
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日    HH:mm:ss     ");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);

        publishInformation.put("time", str);
        publishInformation.put("userName", userName);
        publishInformation.put("ideaBody", ideaBody);
        publishInformation.saveInBackground(new SaveCallback() {
            @Override
            public void done(ParseException e) {
                Toast.makeText(BaseApplication.applicationContext, "发表成功", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public static void publishPicture(final String userName, final String ideaBody, final Bitmap publishPicture) {
        ParseObject publishInformation = new ParseObject("personalIdea");
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日    HH:mm:ss     ");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
         String str = formatter.format(curDate);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        publishPicture.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
        byte[] datas = outputStream.toByteArray();
        ParseFile pf = new ParseFile("icon.png", datas);
        //pf.saveInBackground();
        //query.whereEqualTo("time", str);
        publishInformation.put("time", str);
        publishInformation.put("userName", userName);
        publishInformation.put("ideaBody", ideaBody);
        publishInformation.put("publishPicture", pf);
        publishInformation.saveInBackground(new SaveCallback() {
            @Override
            public void done(ParseException e) {
                Toast.makeText(BaseApplication.applicationContext, "发表成功", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public static void setPublishBitmap(final ParseObject list, final ImageView imageView) {

        ParseFile file = list.getParseFile("publishPicture");
        file.getDataInBackground(new GetDataCallback() {
            @Override
            public void done(byte[] data, com.parse.ParseException e) {
                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                imageView.setImageBitmap(bitmap);
            }
        });

    }
    public static void setBackground(final String userName,final ImageView imageView){
        ParseQuery<ParseObject> query = ParseQuery.getQuery("accountPicture");
        query.whereEqualTo("userName", userName);
        query.getFirstInBackground(new GetCallback<ParseObject>() {
            @Override
            public void done(ParseObject object, ParseException e) {
                if (object != null) {
                    ParseFile file = object.getParseFile("background");
                if (file!=null){
                    file.getDataInBackground(new GetDataCallback() {
                        @Override
                        public void done(byte[] data, com.parse.ParseException e) {
                            if (data != null) {
                                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                                imageView.setImageBitmap(bitmap);
                            }
                        }
                    });}
                }
            }
        });
    }
    public static void publishBackgroundPicture(final String userName, final Bitmap backGroundPicture) {
        final ParseObject accountInformation = new ParseObject("accountPicture");

        ParseQuery<ParseObject> query = ParseQuery.getQuery("accountPicture");
        query.whereEqualTo("userName", userName);
        query.getFirstInBackground(new GetCallback<ParseObject>() {
            @Override
            public void done(ParseObject object, ParseException e) {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                backGroundPicture.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                byte[] datas = outputStream.toByteArray();
                ParseFile pf = new ParseFile("icon.png", datas);
                pf.saveInBackground();
                if (object == null) {
                    accountInformation.put("userName", userName);
                    accountInformation.put("background", pf);
                    accountInformation.saveInBackground(new SaveCallback() {
                        @Override
                        public void done(ParseException e) {
                            Toast.makeText(BaseApplication.applicationContext, "背景已保存", Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    object.put("background", pf);
                    object.saveInBackground(new SaveCallback() {
                        @Override
                        public void done(ParseException e) {
                            Toast.makeText(BaseApplication.applicationContext, "背景已更新", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    public static void gettingData(String userNamefinal, final List<ParseObject> list, final Succeed listener) {
        EMChatManager.getInstance().getChatOptions().setUseRoster(true);
        try {
            friendList = EMContactManager.getInstance().getContactUserNames();
            friendList.add(userNamefinal);
        } catch (EaseMobException e) {
            e.printStackTrace();
        }
        parseObject=new ParseObject("personalIdea");
        ParseQuery<ParseObject> query = ParseQuery.getQuery("personalIdea");
        query.whereContainedIn("userName", friendList);
        query.findInBackground(new FindCallback<ParseObject>() {
            @Override
            public void done(List<ParseObject> objects, ParseException e) {
                for (int i = 0; i < objects.size(); i++) {
                    list.add(objects.get(objects.size() - i - 1));
                }
                listener.ok(list);
                Toast.makeText(BaseApplication.applicationContext, "加载完成", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public static void comment(String time, final String userName, final String commentBody,final Succeed listener, final int position) {
        final List<String> single = new ArrayList<>();
        final List<List<String>> body = new ArrayList<>();
        single.add(userName);
        single.add(commentBody);
        ParseQuery<ParseObject> query = ParseQuery.getQuery("personalIdea");
        body.add(single);
        query.whereEqualTo("time", time);
        query.getFirstInBackground(new GetCallback<ParseObject>() {
            @Override
            public void done(ParseObject object, ParseException e) {
                if (object.get("comments") != null) {
                    List<List<String>> hehe = (List<List<String>>) object.get("comments");
                    hehe.add(single);
                    object.put("comments",hehe);
                    object.saveInBackground(new SaveCallback() {
                        @Override
                        public void done(ParseException e) {

                            //List<List<String>> refresh = new ArrayList<>();
                            //refresh.add(single);
                            listener.refreshComment();
                            //EventBus.getDefault().post(new CommentEty(position,refresh));
                            Toast.makeText(BaseApplication.applicationContext, "评论成功", Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    object.put("comments", body);
                    object.saveInBackground(new SaveCallback() {
                        @Override
                        public void done(ParseException e) {
                            //List<List<String>> refresh = new ArrayList<>();
                            //refresh.add(single);
                            //EventBus.getDefault().post(new CommentEty(position,refresh));
                            listener.refreshComment();
                            Toast.makeText(BaseApplication.applicationContext, "评论成功", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    public static void praise(String time, final String userName, final Succeed listener,int position) {
     final List<String> praiseName = new ArrayList<>();
        ParseQuery<ParseObject> query = ParseQuery.getQuery("personalIdea");
        praiseName.add(userName);
        query.whereEqualTo("time", time);
        query.getFirstInBackground(new GetCallback<ParseObject>() {
            @Override
            public void done(ParseObject object, ParseException e) {
                if (object.get("praise") != null) {
                    List<String> heihei = (List<String>) object.get("praise");
                    if (!heihei.contains(userName)){
                    heihei.add(userName);
                    object.put("praise",heihei);
                    object.saveInBackground(new SaveCallback() {
                        @Override
                        public void done(ParseException e) {
                            listener.refreshPraise();
                            Toast.makeText(BaseApplication.applicationContext, "已赞", Toast.LENGTH_SHORT).show();
                        }
                    });}
                } else {
                    object.put("praise", praiseName);
                    object.saveInBackground(new SaveCallback() {
                        @Override
                        public void done(ParseException e) {
                            listener.refreshPraise();
                            Toast.makeText(BaseApplication.applicationContext, "已赞", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    public interface Succeed {
        void refreshPraise();//刷新赞
        void refreshComment();//刷新评论
        void ok(List<ParseObject> list);//刷新页面

    }


}


